package com.zzyl.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.ElderBindDto;
import com.zzyl.dto.ElderDto;
import com.zzyl.entity.Elder;
import com.zzyl.entity.MemberElder;
import com.zzyl.exception.BusinessException;
import com.zzyl.mapper.CustomerMemberElderMapper;
import com.zzyl.service.CustomerMemberElderService;
import com.zzyl.service.ElderService;
import com.zzyl.utils.IdCardValidator;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.ElderVo;
import com.zzyl.vo.MemberElderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CustomerMemberElderServiceImpl implements CustomerMemberElderService {

    @Autowired
    private ElderService elderService;

    @Autowired
    private CustomerMemberElderMapper  customerMemberElderMapper;

    @Transactional
    @Override
    public String addOrBindFamily(ElderBindDto elderBindDto) {
        String idCard = elderBindDto.getIdCard();
        String name = elderBindDto.getName();

        // 1. 身份证验证
        try {
            IdCardValidator.validate(idCard);
        } catch (IllegalArgumentException e) {
            throw new BusinessException("身份证格式不正确");
        }

        // 2. 查询老人是否已存在
        ElderVo existingElder = elderService.selectByIdCard(idCard);
        Long elderId;
        boolean isNewElder = false;

        if (existingElder != null) {
            // 老人已存在，使用现有老人ID
            elderId = existingElder.getId();
            log.info("老人已存在，进行绑定操作，老人ID: {}", elderId);
        } else {
            // 老人不存在，创建新老人
            Elder elder = new Elder();
            elder.setName(name);
            elder.setIdCardNo(idCard);

            // 从身份证提取信息
            LocalDate birthDate = IdCardValidator.extractBirthDate(idCard);
            int genderCode = IdCardValidator.extractGender(idCard);
            elder.setSex(String.valueOf(genderCode));
            // 保存老人信息
            ElderDto elderDto = new ElderDto();
            BeanUtils.copyProperties(elder, elderDto);
            elder.setStatus(0);
            elderDto.setPhone(String.valueOf(123));
            elderService.insert(elderDto);
            elderId = elderDto.getId();
            isNewElder = true;
            log.info("创建新老人成功，老人ID: {}", elderId);
        }

        // 3. 检查是否已绑定
        Long memberId = UserThreadLocal.getUserId();
        MemberElder existingRelation = customerMemberElderMapper.selectByMemberAndElder(memberId, elderId);
        if (existingRelation != null) {
            throw new BusinessException("该家人已被绑定，请勿重复操作");
        }

        // 4. 创建绑定关系
        MemberElder memberElder = new MemberElder();
        memberElder.setMemberId(memberId);
        memberElder.setElderId(elderId);
        memberElder.setRemark(elderBindDto.getRemark());

        int result = customerMemberElderMapper.insert(memberElder);
        if (result <= 0) {
            throw new BusinessException("操作失败，请重试");
        }

        log.info("用户 {} {}老人 {}，绑定关系创建成功",
                memberId, isNewElder ? "添加" : "绑定", elderId);

        return isNewElder ? "添加成功" : "绑定成功";
    }

    @Override
    public List<MemberElderVo> getMyFamily() {
        Long memberId = UserThreadLocal.getUserId();
        // 查询绑定关系
        List<MemberElder> memberElders = customerMemberElderMapper.selectByMemberId(memberId);

        if (CollectionUtils.isEmpty(memberElders)) {
            return Collections.emptyList();
        }

        // 提取老人ID列表
        List<Long> elderIds = memberElders.stream()
                .map(MemberElder::getElderId)
                .collect(Collectors.toList());

        // 批量查询老人信息
        List<Elder> elders = elderService.listByIds(elderIds);
        Map<Long, Elder> elderMap = elders.stream()
                .collect(Collectors.toMap(Elder::getId, Function.identity()));

        // 组装返回结果
        return memberElders.stream().map(binding -> {
            Elder elder = elderMap.get(binding.getElderId());
            if (elder == null) {
                return null;
            }

            MemberElderVo vo = new MemberElderVo();
            vo.setId(binding.getId());
            vo.setMemberId(binding.getMemberId());
            vo.setMemberName(binding.getMemberName());
            vo.setElderId(binding.getElderId());
            vo.setElderName(elder.getName());
            vo.setRemark(elder.getRemark());
            vo.setCreateTime(elder.getCreateTime());
            vo.setUpdateTime(elder.getUpdateTime());
            vo.setCreateBy(elder.getCreateBy());
            vo.setUpdateBy(elder.getUpdateBy());
            vo.setUpdater(elder.getUpdater());

            return vo;
        }).filter(Objects::nonNull).collect(Collectors.toList());
    }

    @Override
    public PageResponse<MemberElderVo> getMyFamilyByPage(Long memberId, Integer pageNum, Integer pageSize) {
        // 启动分页
        PageHelper.startPage(pageNum, pageSize);
        // 执行分页查询 - 直接获取Page对象
        Page<MemberElderVo> page = customerMemberElderMapper.selectVoByMemberId(memberId);
        // 转换为统一响应
        return PageResponse.of((List<MemberElderVo>) page);
    }

}
